package com.faithbj.common.service.impl;

import com.faithbj.common.model.Region;
import com.faithbj.common.dao.RegionDao;
import com.faithbj.common.service.RegionService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * region的操作业务逻辑
 * @author m
 *
 */
@Service("regionService")
public class RegionServiceImpl extends BaseServiceImpl<Region, String> implements RegionService{

	@Resource
	private RegionDao regionDao;
	
	@Resource(name = "regionDao")
	public void setBaseDao(RegionDao regionDao)
	{
		super.setBaseDao(regionDao);
	}
	
	@Override
	@Transactional(readOnly=true)
	public List<Region> getChildByRegionId(String regionId) {
		Region region=regionDao.get(regionId);
		List<Region> children=new ArrayList<Region>(region.getChildren());
		return children;
	}

	@Override
	@Transactional(readOnly=true)
	public List<Region> getRegionListByType(Integer regionType) {
		List<Region> regions=regionDao.findAny("from Region where regionType=?", regionType);
		return regions;
	}

	@Override
	@Transactional(readOnly=true)
	public Region getRegionById(String regionId) {
		Region region=regionDao.get(regionId);
		return region;
	}

	@Override
	public List<String> getChildRegionIdByRegionId(String regionId) {
		// TODO Auto-generated method stub
		List<String> result = new ArrayList<String>();
		List<Region> child = this.getChildByRegionId(regionId);
		for(Region region : child) {
			result.add(region.getId());
		}
		return result;
	}

	@Override
	public List<String> getStreetRegionIdById(String regionId) {
		// TODO Auto-generated method stub
		Region region = this.getRegionById(regionId);
		List<String> streetRegionIdList = new ArrayList<String>();
		if(region != null){
			if(region.getRegionType().equals(1)) {
				List<Region> regionList = this.getRegionListByType(Region.STREET);
				for(Region r : regionList) {
					streetRegionIdList.add(r.getId());
				}
			} else if(region.getRegionType().equals(2)) {
				streetRegionIdList = this.getChildRegionIdByRegionId(regionId);
			} else if(region.getRegionType().equals(3)) {
				streetRegionIdList.add(regionId);
			}
		}		
		return streetRegionIdList;		
	}

	@Override
	@Transactional(readOnly=true)
	public Region getRegionByCode(String regionCode) {
		Region region=regionDao.get("code", regionCode);
		return region;
	}

	@Override
	public List<Region> getRegionListByCurrentUser()
	{
		return regionDao.getRegionListByCurrentUser();
	}
}
